package com.youbug.kefu.interceptor;

import com.youbug.kefu.constant.SystemConstant;
import com.youbug.kefu.exception.NoLoginException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);

        List<String> permission = (List<String>)request.getSession().getAttribute(SystemConstant.PERMISSION);
        List<String> loginAccess = Arrays.asList("common","useDic");// 登录后可以访问的controller
        List<String> nologinAccess = Arrays.asList("portal");// 不登录可以访问的controller

        String controllerPath = requestURI.split("/")[1];

        if(nologinAccess.contains(controllerPath)){
            return true;
        }
        if("/login".equals(requestURI)
                || requestURI.startsWith("/client")//客户端页面请求不拦截
                || requestURI.startsWith("/keepalive")//保持会话的请求不拦截
                || requestURI.startsWith("/kaptcha")//生成请求不拦截
                ){//使用字典的请求不拦截
            return true;
        }else{
            if(permission == null){
                if(nologinAccess.contains(controllerPath)){
                    return true;
                }
                throw new NoLoginException("登录超时或未登录，请重新登录");
            }else{
                if(loginAccess.contains(controllerPath)){
                    return true;
                }
                if(permission.contains(controllerPath)){
                    return true;
                }else{
                    throw  new RuntimeException("缺少访问权限");
                }
            }
        }
    }
}
